package com.example.multilevelapprovalback.controller;

import com.example.multilevelapprovalback.mapper.UserMapper;
import com.example.multilevelapprovalback.pojo.Result;
import com.example.multilevelapprovalback.pojo.User;
import com.example.multilevelapprovalback.service.UserService;
import com.example.multilevelapprovalback.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Validated
/**
 * 用户登录管理
 */
@Slf4j
@RestController
public class LoginController {
    @Autowired
    private UserService userService;
    @PostMapping("/login")//用户登录
    public Result login(@RequestBody User user , @RequestParam(defaultValue = "false") boolean remember) {
        System.out.println("user"+user);
        User temp=new User();
        System.out.println("密码"+user.getPassword());
        temp.setJobNumber(user.getJobNumber());
        temp.setPassword(user.getPassword());
        System.out.println("工号"+user.getJobNumber());
        User u = userService.login(temp);
        System.out.println("Received request body: " + user.toString());
        System.out.println("Remember me flag from request: " + remember);
        log.info("Response result: {}", Result.success(u));
        //登录成功，生成令牌，下发令牌
        if (u != null) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("id",u.getId());
            claims.put("name",u.getName());
            claims.put("roleId",u.getRoleId());
            System.out.println("角色"+u.getRoleId());
            String jwt = JwtUtils.generateJwt(claims);  //jwt包含了当前登录的员工信息
            u.setToken(jwt);
            System.out.println(remember);
            //尝试增加记住我功能
            if (remember) {
                // 设置JWT Token的cookie，有效期为七天
                HttpHeaders headers = new HttpHeaders();
                headers.set(HttpHeaders.SET_COOKIE, "token=" + jwt + "; Max-Age=604800; Path=/");  // 604800秒等于七天
                // 可能还需要设置HttpOnly和Secure标志，视具体应用的安全需求而定
            }
            return ResponseEntity.status(HttpStatus.OK).body(Result.success(u)).getBody();
        }
        // 登录失败，返回错误信息
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Result.error("用户名或密码错误")).getBody();
    }
}
